// models/Workflow.js
const { pool } = require('../config/database');

class Workflow {
  // 创建新工作流
  static async create(workflowData) {
    const { name, description, nodes_data, edges_data, created_by } = workflowData;
    
    const [result] = await pool.execute(
      `INSERT INTO workflows (name, description, nodes_data, edges_data, created_by) 
       VALUES (?, ?, ?, ?, ?)`,
      [name, description, JSON.stringify(nodes_data), JSON.stringify(edges_data), created_by]
    );
    
    return result.insertId;
  }
  
  // 根据ID获取工作流
  static async findById(id) {
    const [rows] = await pool.execute(
      `SELECT * FROM workflows WHERE id = ? AND is_active = true`,
      [id]
    );
    
    if (rows.length === 0) return null;
    
    const workflow = rows[0];
    workflow.nodes_data = JSON.parse(workflow.nodes_data);
    workflow.edges_data = JSON.parse(workflow.edges_data);
    
    return workflow;
  }
  
  // 获取用户的所有工作流
  static async findByUser(userId) {
    const [rows] = await pool.execute(
      `SELECT * FROM workflows WHERE created_by = ? AND is_active = true ORDER BY updated_at DESC`,
      [userId]
    );
    
    return rows.map(row => ({
      ...row,
      nodes_data: JSON.parse(row.nodes_data),
      edges_data: JSON.parse(row.edges_data)
    }));
  }
  
  // 更新工作流
  static async update(id, updateData) {
    const { name, description, nodes_data, edges_data } = updateData;
    
    const [result] = await pool.execute(
      `UPDATE workflows 
       SET name = ?, description = ?, nodes_data = ?, edges_data = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE id = ?`,
      [name, description, JSON.stringify(nodes_data), JSON.stringify(edges_data), id]
    );
    
    return result.affectedRows > 0;
  }
  
  // 软删除工作流
  static async delete(id) {
    const [result] = await pool.execute(
      `UPDATE workflows SET is_active = false WHERE id = ?`,
      [id]
    );
    
    return result.affectedRows > 0;
  }
  
  // 保存工作流执行记录
  static async saveExecution(executionData) {
    const { workflow_id, status, input_data, output_data, created_by } = executionData;
    
    const [result] = await pool.execute(
      `INSERT INTO workflow_executions (workflow_id, status, input_data, output_data, created_by) 
       VALUES (?, ?, ?, ?, ?)`,
      [workflow_id, status, JSON.stringify(input_data), JSON.stringify(output_data), created_by]
    );
    
    return result.insertId;
  }
  
  // 获取工作流的执行历史
  static async getExecutions(workflowId) {
    const [rows] = await pool.execute(
      `SELECT * FROM workflow_executions 
       WHERE workflow_id = ? 
       ORDER BY started_at DESC 
       LIMIT 50`,
      [workflowId]
    );
    
    return rows.map(row => ({
      ...row,
      input_data: JSON.parse(row.input_data),
      output_data: JSON.parse(row.output_data)
    }));
  }
  
  // 更新执行状态
  static async updateExecutionStatus(executionId, status, outputData = null) {
    let query = `UPDATE workflow_executions SET status = ?`;
    let params = [status];
    
    if (status === 'completed' || status === 'failed') {
      query += `, completed_at = CURRENT_TIMESTAMP`;
    }
    
    if (outputData) {
      query += `, output_data = ?`;
      params.push(JSON.stringify(outputData));
    }
    
    query += ` WHERE id = ?`;
    params.push(executionId);
    
    const [result] = await pool.execute(query, params);
    return result.affectedRows > 0;
  }
}

module.exports = Workflow;